package com.coocaa.ops.common.core.security.interceptor;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.coocaa.ops.common.core.base.model.R;
import com.coocaa.ops.common.core.security.annotation.MyGuard;
import com.coocaa.ops.common.core.security.util.SecurityUtil;
import com.coocaa.ops.common.tool.http.HttpCodeEnums;
import com.coocaa.ops.common.tool.http.HttpSessionUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author bijiahao
 * @date : 2019/10/12.
 * @description 安全 守卫拦截器
 *
 */
@Slf4j
public class MyGuardInterceptor extends HandlerInterceptorAdapter {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (!handler.getClass().isAssignableFrom(HandlerMethod.class)) {
            return true;

        }
        if (isDebug(request)) {
            return true;
        }
        HandlerMethod method = ((HandlerMethod) handler);
        MyGuard authPassport = method.getMethodAnnotation(MyGuard.class);
        if (null == authPassport || !authPassport.require()) {
            return true;
        }
        if (SecurityUtil.verifySign(null, request)) {
            return true;
        }
        this.responseNoAuthority(response);
        return false;
    }


    private boolean isDebug(HttpServletRequest request) {
        String host = HttpSessionUtil.getLocalName(request);
        log.debug("localName: " + host);
        return "1".equals(request.getParameter("debug"))
                && "localhost".equals(host)
                ;
    }


    private void responseNoAuthority(HttpServletResponse response) {
        response.setContentType("application/json;charset=UTF-8");
        R result = R.error(HttpCodeEnums.FORBIDDEN.value().toString(), "No auth");
        response.setStatus(403);
        byte[] bytes = JSON.toJSONBytes(result, new SerializerFeature[]{SerializerFeature.DisableCircularReferenceDetect});
        try {
            response.getOutputStream().write(bytes);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
